import { createDeepSeek } from '@ai-sdk/deepseek';

// Model provider configuration
interface ModelProviderConfig {
  apiKey?: string;
  baseURL?: string;
}

// Default configuration
const defaultConfig: ModelProviderConfig = {
  apiKey: process.env.DEEPSEEK_API_KEY || "sk-e2a8ff503de74636bd62c9089ba694f5",
};

// Validate API key
function validateApiKey(apiKey: string): boolean {
  return apiKey && apiKey.startsWith('sk-') && apiKey.length > 10;
}

// Create a model instance with specified model name
export const createModel = (modelName: string = 'deepseek-chat') => {
  const apiKey = defaultConfig.apiKey;

  if (!validateApiKey(apiKey!)) {
    console.warn('DeepSeek API key appears to be invalid or missing');
    console.warn('Current API key:', apiKey ? `${apiKey.substring(0, 10)}...` : 'undefined');
  }

  console.log(`Creating DeepSeek model: ${modelName}`);
  console.log(`API Key status: ${apiKey ? 'Present' : 'Missing'}`);

  try {
    const provider = createDeepSeek({
      apiKey: defaultConfig.apiKey,
      baseURL: defaultConfig.baseURL,
    });
    return provider.chat(modelName);
  } catch (error) {
    console.error('Failed to create DeepSeek model:', error);
    throw new Error(`Model creation failed: ${error instanceof Error ? error.message : 'Unknown error'}`);
  }
};

// Initialize DeepSeek model provider
export const initializeModelProvider = (config: ModelProviderConfig = defaultConfig) => {
  return createDeepSeek({
    apiKey: config.apiKey || defaultConfig.apiKey,
    baseURL: config.baseURL || defaultConfig.baseURL,
  });
};

// Get default model provider
export const getModelProvider = () => {
  return initializeModelProvider();
};